import java.rmi.*;
import java.rmi.server.*;
import java.io.*;
import java.rmi.registry.*;

/**
 * Class that acts as an implementation of FileReceiver
 * to receive files
 **/
public class RemoteReceiver extends UnicastRemoteObject implements FileReceiver 
{
	// actual place to receive files to
	private String m_directory;

	/**
	 * Make a remote receiver
	 **/
	public RemoteReceiver() throws RemoteException 
	{
	  	try
	  	{
	  		Registry reg = LocateRegistry.createRegistry(8080);
	  		reg.bind("receiver", this);
	  	}
	  	catch (AlreadyBoundException abe)
	  	{
	  		System.err.println(abe.getMessage());
	  	}
	  	catch (Exception e)
	  	{
	  		System.err.println(e.getMessage());
	  	}
	}

	/**
	 * Set the directory where things should be uploaded to
	 * @param directory the directory to place files in
	 **/
	public void setDirectory( String directory ) throws RemoteException
	{
		m_directory = directory;
	}

	/**
	 * Actually receive a file
	 * @param packet The packet to receive
	 * @exception RemoteException
	 **/
	public void receiveFile( FilePacket packet ) throws RemoteException 
	{
		try
		{
			FileOutputStream fos = new FileOutputStream( packet.getFileName() );
			
			packet.writeTo( fos );
		}
		catch( FileNotFoundException fnfe )
		{
			System.out.println( fnfe.getMessage() + " fileName: " + packet.getFileName() );
		}
		catch( IOException e )
		{
			e.printStackTrace();
		}
 	}

	public static void main( String args[] ) 
	{
		String usage = "Usage: java RemoteReceiver";
		try
		{
  		
//			if( args.length != 1 )
//			{
//				System.out.println( usage );
//				System.exit( 0 );
//			}

			RemoteReceiver remote = new RemoteReceiver();
//			remote.setDirectory( args[0] );
		}	
		catch( Exception e )
		{
			e.printStackTrace();
			System.out.println( usage );
		}
	}
} // class RemoteReceiver
